import json

from django.http import JsonResponse
from backend.models import UserInfo
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods


@csrf_exempt
@require_http_methods(['GET'])
# Create your backend_views here.
# 注册接口
def register(request):
    response = {}
    try:
        username = request.GET.get('username')
        password = request.GET.get('password')
        phoneNumber = request.GET.get('phoneNumber')
        email = request.GET.get('email')
        danceType = request.GET.get('danceType')
        if UserInfo.objects.filter(username=username):
            response['msg'] = '用户名已存在'
            response['respCode'] = '1'
        elif UserInfo.objects.filter(phone_number=phoneNumber):
            response['msg'] = '手机号已存在'
            response['respCode'] = '2'
        elif UserInfo.objects.filter(email=email):
            response['msg'] = '邮箱已存在'
            response['respCode'] = '3'
        else:
            UserInfo.objects.create(username=username, password=password, phone_number=phoneNumber, email=email,
                                    danceType=danceType)
            response['msg'] = 'success'
            response['respCode'] = '000000'
    except Exception as e:
        response['msg'] = str(e)
        response['respCode'] = '999999'
    return JsonResponse(response)


# 登录接口
def login(request):
    response = {}
    try:
        username = request.GET.get('username')
        password = request.GET.get('password')
        if username:
            user = UserInfo.objects.get(username=username)
            if user:
                if user.password == password:
                    response['msg'] = 'success'
                    response['respCode'] = '000000'
    except Exception as e:
        response['msg'] = str(e)
        response['respCode'] = '999999'
    return JsonResponse(response)


# 修改密码接口
@csrf_exempt
@require_http_methods(['POST'])
def password_edit(request):
    response = {}
    try:
        body = json.loads(request.body)
        UserInfo.objects.filter(id=body['form']['id']).update(password=body['form']['current_password'])
        response['respCode'] = '000000'
        response['respMsg'] = 'success'
    except Exception as e:
        response['respCode'] = '999999'
        response['respMsg'] = str(e)
    return JsonResponse(response)

